<template>
  <section class="component warehousing-apply">
    <el-form
      :model="fromData"
      :rules="rules"
      ref="ruleForm"
      label-width="110px"
      class="demo-ruleForm"
    >
      <template v-if="isCarManageMenu">
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单编号：">
              {{ rowData.caseNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次号：">
              {{ rowData.batchNumber }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上牌地：">
              {{ rowData.boardAddress }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车牌号：">
              {{ rowData.plateNum }}
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <el-row>
        <el-col :span="12">
          <el-form-item label="车库：" prop="garageInfoId">
            <el-select
              placeholder="请选择"
              v-model="fromData.garageInfoId"
              clearable
            >
              <el-option
                v-for="{ index, id, garageName } in garageList"
                :key="index"
                :label="garageName"
                :value="id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="库管：" prop="userId">
            <el-select placeholder="请选择" v-model="fromData.userId" clearable>
              <el-option
                v-for="{ index, realName, userId } in userList"
                :key="index"
                :label="realName"
                :value="userId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="年检到期日期：" prop="inspectionDate">
            <el-date-picker
              v-model="fromData.inspectionDate"
              :picker-options="pickerOptions"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公里数：" prop="kilometres">
            <el-input
              v-model.trim="fromData.kilometres"
              maxlength="7"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="评估价：" prop="valuationPrice">
            <el-input
              v-model.trim="fromData.valuationPrice"
              maxlength="15"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="VIN码：">
            {{ this.carFrameNo }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="钥匙数量：" prop="keysNumber">
            <el-select
              placeholder="请选择"
              v-model="fromData.keysNumber"
              clearable
            >
              <el-option
                v-for="{ index, name, code } in $dict.getDictData('KeysNumber')"
                :key="index"
                :label="name"
                :value="code"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否有行驶证：" prop="haveNotFlag">
            <el-select
              placeholder="请选择"
              v-model="fromData.haveNotFlag"
              clearable
            >
              <el-option
                v-for="{ index, name, code } in $dict.getDictData('CommonFlag')"
                :key="index"
                :label="name"
                :value="code"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注：" prop="remark">
        <el-input
          type="textarea"
          v-model="fromData.remark"
          style="width:97%"
          maxlength="300"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="车辆图片：" prop="name">
        <flie-upload
          :listType="'picture-card'"
          :fileList.sync="fileList"
          :AllowExtension="['jpg', 'png', 'jpeg']"
        />
      </el-form-item>

      <template v-if="isCarManageMenu">
        <el-form-item label="审核记录：">
          <data-box :data="rowData.warehouseRecords">
            <template slot="columns">
              <el-table-column
                prop="type"
                label="审核类型"
                :formatter="
                  row => $filter.dictConvert(row.type, 'CarApprovalType')
                "
                :min-width="$helper.getColumnWidth(5)"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="operatorRealName"
                label="审核人"
                :min-width="$helper.getColumnWidth(5)"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="createTime"
                label="审核时间"
                :formatter="row => $filter.dateTimeFormat(row.createTime)"
                :min-width="$helper.getColumnWidth(5)"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="carApplyStatus"
                label="审核结果"
                :formatter="
                  row => $filter.dictConvert(row.carApplyStatus, 'ApplyStatus')
                "
                :min-width="$helper.getColumnWidth(5)"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="remark"
                label="备注"
                :min-width="$helper.getColumnWidth(5)"
                show-overflow-tooltip
              >
              </el-table-column>
            </template>
          </data-box>
        </el-form-item>
      </template>
    </el-form>

    <div class="operate-buttons">
      <el-button @click="EmitClose">取消</el-button>
      <el-button @click="commit" :loading="loading">确定</el-button>
    </div>
  </section>
</template>
<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import FlieUpload from "~/components/common/file-upload.vue";
import { Emit, Prop, Inject, Watch } from "vue-property-decorator";
import DataBox from "~/components/common/data-box.vue";
import { CarManageService } from "~/services/domain-service/car-manage.service";
import { Dependencies } from "~/core/decorator";
import { namespace } from "vuex-class";
import { FileUploadService } from "~/services/file-service/file-upload.service";

const CollectionExecutionModule = namespace("collection-execution");

@Component({
  components: {
    FlieUpload,
    DataBox
  }
})
export default class WarehousingApply extends Vue {
  @Prop({ default: false }) private isCarManageMenu;
  @Dependencies(CarManageService) private carManageService: CarManageService;
  @Dependencies(FileUploadService) private fileUploadService: FileUploadService;
  @Prop() private carFrameNo;
  @Prop() private caseIds;
  @Prop() private rowData;

  private fromData: any = {
    id: "",
    garageInfoId: "",
    userId: "",
    inspectionDate: "",
    kilometres: "",
    valuationPrice: "",
    warehouseCarStatus: "IN_WAREHOUSE_WAIT_APPROVED",
    remark: "",
    imageIds: [],
    haveNotFlag: "",
    caseId: "",
    keysNumber: ""
  };
  private fileList: any = [];
  private loading: boolean = false;
  private rules: any = {
    garageInfoId: { required: true, message: "请选择车库" },
    userId: { required: true, message: "请选择库管" },
    inspectionDate: { required: true, message: "请选择年检到期日期" },
    kilometres: [
      { required: true, message: "请输入公里数" },
      { validator: this.validatePass }
    ],
    keysNumber: { required: true, message: "请选择钥匙数量" },
    haveNotFlag: { required: true, message: "请选择是否有驾驶证" },
    valuationPrice: [{ validator: this.validatePass }]
  };
  private pickerOptions: any = {
    disabledDate: time => {
      return time.getTime() < Date.now() - 3600 * 1000 * 24;
    }
  };
  private garageList: any = [];
  private userList: any = [];

  @Emit("close") private EmitClose() {
    this.reset();
  }

  @Watch("fromData.garageInfoId") private change(val) {
    if (!val) {
      this.userList = [];
      this.fromData.userId = "";
    } else {
      this.carManageService.getGarageUsersById(val).subscribe(data => {
        this.userList = data;
      });
    }
  }

  private validatePass(rule: any, value: any, callback: any) {
    const validateNumber = /^[0-9]*$/;
    if (!validateNumber.test(value)) callback(new Error("必须是数字！"));
    callback();
  }

  private commit() {
    const from: any = this.$refs["ruleForm"];
    from.validate(valid => {
      if (!valid) return;
      this.loading = true;
      this.carManageService
        .updateWarehouseCar(this.dataPramas())
        .subscribe(data => {
          this.closeLoading();
          this.$message.success("操作成功！");
          this.EmitClose();
        }, this.closeLoading);
    });
  }

  private getGarageList() {
    this.referData();
    this.carManageService.getAllGaragesList().subscribe(data => {
      this.garageList = data;
    });
  }

  private referData() {
    if (this.isCarManageMenu) {
      this.fromData.id = this.rowData.id;
      this.fromData.garageInfoId = this.rowData.garageInfoId;
      this.fromData.userId = this.rowData.userId;
      this.fromData.inspectionDate = this.rowData.inspectionDate;
      this.fromData.kilometres = this.rowData.kilometres;
      this.fromData.keysNumber = this.rowData.keysNumber;
      this.fromData.remark = this.rowData.remark;
      this.fromData.haveNotFlag = this.rowData.haveNotFlag;
      this.fromData.warehouseCarStatus = "IN_WAREHOUSE_WAIT_APPROVED";
      this.fromData.valuationPrice = this.rowData.valuationPrice;
      this.imageFileList(this.rowData.imageIds);
    }
  }

  private closeLoading() {
    this.loading = false;
  }

  private imageFileList(val) {
    if (!val) return;
    this.fileUploadService.getAllUploadFileByIds(val).subscribe(data => {
      this.fileList = data;
      this.fileList.map(v => {
        v.response = {};
        v.response.id = v.id;
        v.response.url = v.url;
      });
    });
  }

  private dataPramas() {
    const params: any = { ...this.fromData };
    params.valuationPrice = parseInt(this.fromData.valuationPrice);
    params.kilometres = parseInt(this.fromData.kilometres);
    params.inspectionDate = this.$filter.dateFormat(
      this.fromData.inspectionDate
    );
    params.imageIds = this.fileList.map(v => v.response.id);
    params.caseId = this.isCarManageMenu
      ? this.rowData.caseId
      : this.caseIds[0];
    const user = this.userList.find(v => v.userId === this.fromData.userId);
    params.userName = user.realName;
    return params;
  }

  private reset() {
    const from: any = this.$refs["ruleForm"];
    from.resetFields();
    this.fileList = [];
  }
}
</script>
<style lang="less">
.component.warehousing-apply {
  max-height: 533px;
  overflow-y: auto;
}
</style>
